package org.beian.fmmall.controller;

import com.github.wxpay.sdk.WXPay;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.beian.fmmall.VO.ResStatus;
import org.beian.fmmall.VO.ResultVO;
import org.beian.fmmall.beans.Orders;
import org.beian.fmmall.config.MyPayConfig;
import org.beian.fmmall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/order")
@Api(tags = "订单管理",value = "提供订单管理相关接口")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @PostMapping("/add")
    @ApiOperation("添加订单")
    public ResultVO add(String cids,@RequestBody Orders order){
        ResultVO resultVO = null;
        try {
            resultVO = orderService.addOrder(cids, order);
            HashMap<String,String> map = (HashMap<String, String>) resultVO.getData();
            WXPay wxPay = new WXPay(new MyPayConfig());
            HashMap<String,String> data=new HashMap<>();
            data.put("body",map.get("untitled"));//商品描述
            data.put("out_trade_no",map.get("orderId"));//订单编号
            data.put("fee_type","CNY");//币种
//            data.put("total_fee",order.getActualAmount()*100+"");//订单金额
            data.put("total_fee","1");//订单金额
            data.put("trade_type","NATIVE");//支付方式
            data.put("notify_url","http://47.116.32.173:8888/pay/success");//回调函数
            Map<String, String> resp = wxPay.unifiedOrder(data);
            map.put("totalAmount",order.getActualAmount()+"");
            map.put("payUrl",resp.get("code_url"));
        } catch (SQLException e) {
            resultVO=new ResultVO(ResStatus.NO,"提交订单失败！",null);
        } catch (Exception e) {
            resultVO=new ResultVO(ResStatus.NO,"提交订单失败！",null);
        }
        return resultVO;
    }
    @ApiOperation("订单查询接口")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户ID",required = true),
            @ApiImplicitParam(name = "status",value = "订单状态",required = true),
            @ApiImplicitParam(name = "pageNum",value = "当前页码",required = true),
            @ApiImplicitParam(name = "limit",value = "每页条数",required = true),
    })
    public ResultVO roderList(@RequestHeader("token")String token,
                              String userId,String status,int pageNum,int limit){
        return orderService.listOrders(userId, status, pageNum, limit);
    }
}
